import * as check from './check';

export function rule(label, type, required) {
  if (type === true || type === false) {
    required = type;
    type = undefined;
  }
  if (required === undefined) {
    required = true;
  }
  const message = /选择/.test(label) ? `请${label}` : `请输入${label}`;
  if (!type) {
    return [{ required, message }];
  }
  if (_.isArray(type)) {
    return [{ required, message }, ...type];
  }
  if (_.isFunction(type)) {
    return [{ required, message }, { validator: type }];
  }
  if (type === 'name') {
    return [{ required, message }, { min: 2, max: 4, message: '请输入真实姓名' }];
  }
  if (type === 'phone') {
    return [{ required, message }, { validator: check.checkTelePhone }];
  }
  if (type === 'code') {
    return [{ required, message }, { validator: check.checkCode }];
  }
  if (type === 'age') {
    return [{ required, message }, { validator: check.checkAgeNumber }];
  }
  if (type === 'idNo') {
    return [{ required, message }, { validator: check.checkIdNo }];
  }
  // email url date hex boolean number string float integer array object method regexp
  return [{ type, required, message }];
}

export function valid(form) {
  return new Promise(resolve => {
    form.value.validate((valid) => {
      resolve(valid);
    });
  })
}
